<template>
  <div class="app-container">
    <div style="width: 70%; padding: 20px;">
      <ColoredCard title=" 数据说明" description="此页只提供密钥的激活信息，查询激活记录请联系管理员" icon="el-icon-info" cardColor="#5F99AE" />
    </div>
    <el-card class="product-card">
      <!-- Search & Rows Selection -->
      <div class="search-container">
        <el-input v-model="searchQuery" placeholder="搜索产品名称..." clearable class="search-box"
          @keyup.enter.native="fetchLicenseList(1)" />
        <el-button type="primary" @click="fetchLicenseList(1)">搜索</el-button>

        <p style="padding-left: 5%;">每页显示</p>
        <el-select v-model="rows" @change="fetchLicenseList(1)" placeholder="每页显示">
          <el-option v-for="size in [10, 20, 50, 100]" :key="size" :label="`${size} 条`" :value="size" />
        </el-select>
      </div>

      <!-- Pagination & Export Buttons -->
      <div style="display: flex; align-items: center; padding-bottom: 20px; justify-content: space-between;">
        <el-pagination background layout="prev, pager, next" :total="total_items" :page-size="rows"
          @current-change="fetchLicenseList" />

        <div style="display: flex; align-items: center; gap: 10px;">
          <el-select v-model="exportFormat" placeholder="选择导出格式">
            <el-option label="Excel" value="excel" />
            <el-option label="TXT" value="txt" />
          </el-select>

          <!-- 导出按钮 -->
          <el-button :loading="loading" type="primary" @click="downloadFile(false)" icon="el-icon-download">
            下载本页
          </el-button>
          <el-button :loading="loading" type="warning" @click="downloadFile(true)" icon="el-icon-download">
            导出全部
          </el-button>
        </div>
      </div>

      <!-- Data Table -->
      <el-table :data="licenseList" border style="width: 100%">
        <el-table-column prop="id" label="ID" min-width="80" align="center" />
        <el-table-column prop="license_key" label="激活密钥" min-width="200" show-overflow-tooltip />
        <el-table-column prop="product_name" label="产品名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="duration_days" label="有效期 (天)" min-width="80" align="center" />
        <el-table-column prop="activated" label="是否激活" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.activated ? 'success' : 'danger'">
              {{ row.activated ? "已激活" : "未激活" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="activated_at" label="激活时间" min-width="150" align="center">
          <template #default="{ row }">
            {{ row.activated_at ? row.activated_at : "—" }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>


<script>
import { getLicenseList, deleteLicense, getLicenseExcel, getLicenseTxt } from "@/api/license-key";
import ColoredCard from '@/components/ColoredCard/index.vue';
import { Message } from 'element-ui';
import { downloadBinary } from "@/utils/myRequest";

export default {
  name: "LicenseKey",
  data() {
    return {
      searchQuery: "",
      licenseList: [],
      total_items: 0,
      rows: 10, // 选中的每页行数
      page: 1,
      total_page: 0,
      current_page: 0,
      loading: false,
      exportFormat: "excel" // Default format
    };
  },
  components: {
    ColoredCard
  },
  methods: {
    async fetchLicenseList(page = 1) {
      this.page = page;
      try {
        const response = await getLicenseList("created_at", this.rows, this.page, -1, this.searchQuery);
        if (response.success) {
          this.licenseList = response.data.keys.map((item) => ({
            ...item,
            duration_days: item.duration > 10000 ? item.duration / (24 * 60 * 60 * 1000) : item.duration,
            activated: item.activated,
            activated_at: item.activated_at || "",
          }));
          this.total_page = response.data.total_page;
          this.current_page = response.data.current_page;
          this.total_items = this.total_page * this.rows;
        }
      } catch (error) {
        Message.error('获取密钥列表失败!');
      }
    },

    async handleDelete(licenseId) {
      try {
        await deleteLicense(licenseId);
        this.licenseList = this.licenseList.filter(item => item.id !== licenseId);
        this.total_items -= 1; // 更新总数
        Message.success('删除成功!');
      } catch (error) {
        Message.error('删除密钥失败!');
      }
    },

    async downloadFile(exportAll) {
      this.loading = true;
      try {
        if (this.exportFormat === "excel") {
          await this.exportToExcel(exportAll);
        } else if (this.exportFormat === "txt") {
          await this.exportToTxt(exportAll);
        }
      } catch (error) {
        Message.error('导出文件失败! ' + error);
      } finally {
        this.loading = false;
      }
    },

    async exportToExcel(exportAll) {
      try {
        const response = await getLicenseExcel("created_at", this.rows, this.page, -1, this.searchQuery, exportAll);
        if (response.success) {
          const filename = response.data.url.split("/").pop(); // Extract filename from URL
          await downloadBinary(response.data.url, filename);
        } else {
          Message.error("导出Excel失败!");
        }
      } catch (error) {
        Message.error("导出Excel失败! " + error);
      }
    },

    async exportToTxt(exportAll) {
      try {
        const response = await getLicenseTxt("created_at", this.rows, this.page, -1, this.searchQuery, exportAll);
        if (response.success) {
          const filename = response.data.url.split("/").pop(); // Extract filename from URL
          await downloadBinary(response.data.url, filename);
        } else {
          Message.error("导出TXT失败!");
        }
      } catch (error) {
        Message.error("导出TXT失败! " + error);
      }
    }
  },
  mounted() {
    this.fetchLicenseList();
  },
};
</script>


<style scoped>
.app-container {
  width: 100%;
  margin: 0px auto;
}

.product-card {
  width: 100%;
  padding: 5px;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 300px;
}

.el-select {
  width: 120px;
}
</style>
